<template>
  <view class="content">
    <swiper
      autoplay
      indicator-dots
      indicator-color="rgba(0,0,36,.6)"
      indicator-active-color="rgba(0,255,36,.6)"
    >
      <swiper-item
        v-for="item in bannersList"
        :key="item.id"
        @click="goWebPage(item.url)"
      >
        <image :src="item.imagePath" class="img" mode="aspectFit"></image>
      </swiper-item>
    </swiper>
    <askItem
      :news="asks"
      @collectDo="sumitCollect"
      @goPage="goWebPage"
    ></askItem>
  </view>
</template>

<script>
import {
  fecthBanners,
  askLists,
  collected,
  uncollected,
} from "../../api/api.js";
export default {
  data() {
    return {
      bannersList: [],
      asks: [],
      index: 1,
      pageCount: 0,
    };
  },
  onReachBottom() {
    if (this.index > this.pageCount) {
      return;
    }
    this.index++;
    this.getAskList();
  },
  onLoad() {
    this.banners();
    this.getAskList();
  },
  onPullDownRefresh() {
    this.index = 1;
    this.pageCount = 0;
    this.banners();
    this.getAskList();

    uni.stopPullDownRefresh();
  },
  onShow() {},
  methods: {
    sumitCollect(id, index) {
      this.collects(id, index);
    },
    async collects(id, index) {
      let collect = this.asks[index].collect;
      if (collect) {
        //调用取消收藏
        let res = await uncollected(id);

        if (res.errorCode == 0) {
          uni.showToast({
            title: "取消收藏成功！",
          });
        }
      } else {
        //调用收藏接口
        let res = await collected(id).catch((error) => {
          if (error) {
            uni.navigateTo({
              url: "../login/login",
            });
          }
        });
        let { errorCode } = res;
        if (errorCode == -1001) {
          uni.navigateTo({
            url: "/pages/login/login",
          });
        } else {
          uni.showToast({
            title: "收藏成功！",
          });
        }
      }
      this.$set(this.asks[index], "collect", !collect);
    },
    goWebPage(url) {
      uni.navigateTo({
        url: "/pages/webPage/webPage?url=" + url,
      });
    },
    async getAskList() {
      let askList = await askLists(this.index);
      askList = askList.data;
      console.log("ask" + askList.pageCount);
      this.pageCount = Number(askList.pageCount);
      this.asks = this.asks.concat(askList.datas);
    },

    async banners() {
      let res = await fecthBanners();
      this.bannersList = res.data;
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;

  swiper {
    width: 750rpx;
    height: 400rpx;

    .img {
      width: 750rpx;
    }
  }
}
</style>
